package cn.funnymap.lgis.web;

import cn.funnymap.lgis.spring.SpringContextHolder;
import com.alibaba.fastjson2.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

/**
 * @author jiaoxn
 */
public class RestTemplateUtil {
    private static final RestTemplate REST_TEMPLATE = SpringContextHolder.getBean(RestTemplate.class);

    private RestTemplateUtil() {}

    public static JSONObject queryAsJson(URI uri) throws ResourceAccessException {
        String serviceInfoResponseBody = REST_TEMPLATE.getForEntity(uri, String.class).getBody();
        return JSONObject.parseObject(serviceInfoResponseBody);
    }

    public static JSONObject queryAsJson(String url, HttpMethod httpMethod, HttpEntity<?> httpEntity) {
        String response = REST_TEMPLATE.exchange(url, httpMethod, httpEntity, String.class).getBody();
        return JSONObject.parseObject(response);
    }

    @ConditionalOnClass(DocumentHelper.class)
    public static Document queryAsXmlDocument(URI uri) throws DocumentException {
        String responseBody = REST_TEMPLATE.getForEntity(uri, String.class).getBody();

        if (responseBody != null) {
            return DocumentHelper.parseText(responseBody);
        }

        return null;
    }
}
